<?php


namespace process;


use app\util\jt808\Common;
use app\util\jt808\Jt0001;
use app\util\jt808\Jt0100;
use app\util\jt808\MsgDecoder;
use app\util\jt808\MsgEncoder;
use GatewayWorker\Lib\Gateway;
use Workerman\Connection\TcpConnection;

class Jt808
{
    /**
     * 接收上报数据
     * @param TcpConnection $connection
     * @param $message
     * @throws \Exception
     */
    public function onMessage(TcpConnection $connection, $message)
    {
        $clientId = $connection->id;
        $decoder = new MsgDecoder();
        $encoder = new MsgEncoder();
        // $ret 就是解析后的
        $ret = $decoder->getPackageData($message);
        switch ($ret->MsgHeader->msg_id) {
            //通用应答
            case '0001':
                $jt001 = new Jt0001($ret->msg_body);
                break;
            case '0002':
                $response_body = Common::ComResponse($ret->MsgHeader->terminal_phone, '0002', 0);
                $set = [
                    'phone' => $ret->MsgHeader->terminal_phone,
                    'msg_type' => '8001',
                    'flow_id' => 2,
                    'encode_type' => 0
                ];
                $response = $encoder->getResponseString($response_body, $set);
                Gateway::sendToClient($clientId, $response);
                break;
            case '0100':
                // 终端注册,回复注册应答
                $jt = new Jt0100($ret->msg_body);
                $body = $jt->response($ret->MsgHeader->flow_id, 0, 'test_auth_7');
                $set = [
                    'phone' => $ret->MsgHeader->terminal_phone,
                    'msg_type' => '8100',
                    'flow_id' => 2,
                    'encode_type' => 0
                ];
                $response = $encoder->getResponseString($body, $set);
                Gateway::sendToClient($clientId, $response);
                break;
        }
    }
}